# 1. 导包
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, VARCHAR
from sqlalchemy.orm import declarative_base,sessionmaker,Session
from typing import Generator

# 2. 创建连接引擎
engine=create_engine(
   # f"mysql+pymysql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}",
    "mysql+pymysql://root:DIAOling1121@localhost:3306/fast_api",
    echo=True,
    pool_pre_ping=True
)

# 3. # 创建基类 (SQLAlchemy 2.x 推荐用法)
Base = declarative_base()

class User(Base):  # 只要继承Base就是一张数据库表
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True,autoincrement=True)
    name = Column(VARCHAR(50))
    age = Column(Integer)

    # 定义__repr__方法，便于调试时查看对象信息
    def __repr__(self):
        return f"<User(id={self.id}, name='{self.name}', age={self.age})>"


# 4. 开始创建表
Base.metadata.create_all(engine)

# 5. 创建db session
DBSession = sessionmaker(bind=engine)


def get_session() -> Generator[Session, None, None]:
    """获取数据库会话"""
    session = DBSession()
    try:
        yield session
    finally:
        session.close()